import os
from reportlab.lib import colors, pagesizes, units
from reportlab.lib.styles import getSampleStyleSheet, ParagraphStyle
from reportlab.pdfbase import pdfmetrics
from reportlab.pdfbase.ttfonts import TTFont
from reportlab.platypus import SimpleDocTemplate, Paragraph, Spacer, Table, TableStyle, Image, PageBreak

from ..book import Book, ContentType
from ..utils import LOG


class Writer:
    def __init__(self):
        pass

    def save_translated_book(self, book: Book, ouput_file_format: str):
        LOG.debug(ouput_file_format)
        if ouput_file_format.lower() == "pdf":
            out_file_path = self._save_translated_book_pdf(book)
        elif ouput_file_format.lower() == "markdown":
            out_file_path = self._save_translated_book_markdown(book)
        else:
            LOG.error(f"不支持的文件类型：{ouput_file_format}")
            return None

        LOG.info(f"翻译完成，文件保存至：{out_file_path}")
        return out_file_path

    def _save_translated_book_pdf(self, book: Book) -> str:
        out_file_path = book.pdf_file_path.replace('.pdf', '_translated.pdf')
        LOG.info(f"开始导出：{out_file_path}")

        font_path = "../fonts/simsun.ttc"
        pdfmetrics.registerFont(TTFont("SimSun", font_path))

        simsun_style = ParagraphStyle(
            name="SimSun",
            fontName="SimSun",
            fontSize=12,
            leading=14,
            spaceAfter=12,
            alignment=0,  # 左对齐
        )

        doc = SimpleDocTemplate(out_file_path, pagesize=pagesizes.letter)
        styles = getSampleStyleSheet()
        story = []

        for page in book.pages:
            for content in page.contents:
                if content.status:
                    if content.content_type == ContentType.TEXT:
                        text = content.translation if content.translation else content.original
                        paragraph = Paragraph(text, simsun_style)
                        story.append(paragraph)
                        story.append(Spacer(1, 12))
                    elif content.content_type == ContentType.TABLE:
                        table = content.translation if content.translation is not None else content.original

                        # 将表头和数据合并
                        data_for_pdf = [table.columns.tolist()] + table.values.tolist()

                        table_style = TableStyle([
                            ('BACKGROUND', (0, 0), (-1, 0), colors.grey),
                            ('TEXTCOLOR', (0, 0), (-1, 0), colors.whitesmoke),
                            ('ALIGN', (0, 0), (-1, -1), 'CENTER'),
                            ('FONTNAME', (0, 0), (-1, 0), 'SimSun'),  # 更改表头字体为 "SimSun"
                            ('FONTSIZE', (0, 0), (-1, 0), 14),
                            ('BOTTOMPADDING', (0, 0), (-1, 0), 12),
                            ('BACKGROUND', (0, 1), (-1, -1), colors.beige),
                            ('FONTNAME', (0, 1), (-1, -1), 'SimSun'),  # 更改表格中的字体为 "SimSun"
                            ('GRID', (0, 0), (-1, -1), 1, colors.black)
                        ])

                        pdf_table = Table(data_for_pdf, colWidths=[units.inch * 2] * len(table.columns))
                        pdf_table.setStyle(table_style)
                        story.append(pdf_table)

            if page != book.pages[-1]:
                story.append(PageBreak())
        doc.build(story)
        return out_file_path

    def _save_translated_book_markdown(self, book: Book):
        output_file_path = book.pdf_file_path.replace('.pdf', f'_translated.md')

        LOG.info(f"开始导出: {output_file_path}")
        with open(output_file_path, 'w', encoding='utf-8') as output_file:
            # Iterate over the pages and contents
            for page in book.pages:
                for content in page.contents:
                    if content.status:
                        if content.content_type == ContentType.TEXT:
                            # Add translated text to the Markdown file
                            text = content.translation
                            output_file.write(text + '\n\n')

                        elif content.content_type == ContentType.TABLE:
                            # Add table to the Markdown file
                            table = content.translation
                            header = '| ' + ' | '.join(str(column) for column in table.columns) + ' |' + '\n'
                            separator = '| ' + ' | '.join(['---'] * len(table.columns)) + ' |' + '\n'
                            # body = '\n'.join(['| ' + ' | '.join(row) + ' |' for row in table.values.tolist()]) + '\n\n'
                            body = '\n'.join(['| ' + ' | '.join(str(cell) for cell in row) + ' |' for row in table.values.tolist()]) + '\n\n'
                            output_file.write(header + separator + body)

                # Add a page break (horizontal rule) after each page except the last one
                if page != book.pages[-1]:
                    output_file.write('---\n\n')

        return output_file_path
